package org.lightpersist.dao.hibernate;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.lightcommons.util.ReflectionUtils;

public class HibernateAnnotationUtils {
	private HibernateAnnotationUtils(){
		
	}
	
	private static Map<Class, String> idFieldMap = new HashMap<Class, String>();
	
	/**
	 * 获取某个类的id名
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getIdFieldName(Class clazz){
		String idField = idFieldMap.get(clazz);
		if(idField==null){
			if(clazz.getAnnotation(Entity.class)!=null){
				if(ReflectionUtils.getAnnotation(clazz, "id", Id.class)!=null)
					idField= "id";
				else{
					for(String f:ReflectionUtils.getFields(clazz)){
						if(ReflectionUtils.getAnnotation(clazz, f, Id.class)!=null){
							idField = f;
							break;
						}
					}
				}
			}
			idFieldMap.put(clazz, idField);
		}
		return idField;
	}
	
}
